import { NextRequest, NextResponse } from 'next/server';
import { getUserManagement } from '@/lib/user-management';
import { cookies } from 'next/headers';

export async function POST(request: NextRequest) {
  try {
    const { username, password } = await request.json();

    if (!username || !password) {
      return NextResponse.json({
        success: false,
        error: '用户名和密码不能为空'
      }, { status: 400 });
    }

    const userMgmt = getUserManagement();
    const user = await userMgmt.authenticateUser(username, password);

    if (!user) {
      return NextResponse.json({
        success: false,
        error: '用户名或密码错误'
      }, { status: 401 });
    }

    // 创建会话 - 暂时跳过数据库写入，使用简单的token
    let sessionToken = 'temp-session-' + Date.now();

    try {
      sessionToken = userMgmt.createSession(user.id);
    } catch (sessionError) {
      console.log('会话创建失败，使用临时token:', sessionError.message);
      // 继续使用临时token
    }

    // 设置cookie
    const cookieStore = await cookies();
    cookieStore.set('session_token', sessionToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 24 * 60 * 60 // 24小时
    });

    return NextResponse.json({
      success: true,
      data: {
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          full_name: user.full_name,
          role_code: user.role_code,
          role_name: user.role_name
        }
      }
    });

  } catch (error) {
    console.error('登录失败:', error);
    return NextResponse.json({
      success: false,
      error: '登录失败，请稍后重试'
    }, { status: 500 });
  }
}
